using System.IO;
using System.Threading;

namespace winsw
{
	public class SizeBasedRollingLogAppender : AbstractFileLogAppender
	{
		public static int BYTES_PER_KB = 1024;

		public static int BYTES_PER_MB = 1024 * BYTES_PER_KB;

		public static int DEFAULT_SIZE_THRESHOLD = 10 * BYTES_PER_MB;

		public static int DEFAULT_FILES_TO_KEEP = 8;

		private int sizeThreshold;

		private int filesToKeep;

		public SizeBasedRollingLogAppender(string logDirectory, string baseName, int sizeThreshold, int filesToKeep)
			: base(logDirectory, baseName)
		{
			this.sizeThreshold = sizeThreshold;
			this.filesToKeep = filesToKeep;
		}

		public SizeBasedRollingLogAppender(string logDirectory, string baseName)
			: this(logDirectory, baseName, DEFAULT_SIZE_THRESHOLD, DEFAULT_FILES_TO_KEEP)
		{
		}

		public override void log(Stream outputStream, Stream errorStream)
		{
			new Thread((ThreadStart)delegate
			{
				CopyStreamWithRotation(outputStream, ".out.log");
			}).Start();
			new Thread((ThreadStart)delegate
			{
				CopyStreamWithRotation(errorStream, ".err.log");
			}).Start();
		}

		private void CopyStreamWithRotation(Stream data, string ext)
		{
			byte[] array = new byte[1024];
			FileStream fileStream = new FileStream(base.BaseLogFileName + ext, FileMode.Append);
			long num = new FileInfo(base.BaseLogFileName + ext).Length;
			while (true)
			{
				bool flag = true;
				int num2 = data.Read(array, 0, array.Length);
				if (num2 == 0)
				{
					break;
				}
				if (num + num2 < sizeThreshold)
				{
					fileStream.Write(array, 0, num2);
					num += num2;
				}
				else
				{
					int offset = 0;
					for (int i = 0; i < num2; i++)
					{
						if (array[i] == 10 && num + i >= sizeThreshold)
						{
							fileStream.Write(array, offset, i + 1);
							fileStream.Close();
							offset = i + 1;
							try
							{
								for (int num3 = filesToKeep; num3 >= 1; num3--)
								{
									string text = base.BaseLogFileName + "." + (num3 - 1) + ext;
									string text2 = base.BaseLogFileName + "." + (num3 - 2) + ext;
									if (File.Exists(text))
									{
										File.Delete(text);
									}
									if (File.Exists(text2))
									{
										File.Move(text2, text);
									}
								}
								File.Move(base.BaseLogFileName + ext, base.BaseLogFileName + ".0" + ext);
							}
							catch (IOException ex)
							{
								base.EventLogger.LogEvent("Failed to rotate log: " + ex.Message);
							}
							fileStream = new FileStream(base.BaseLogFileName + ext, FileMode.Create);
							num = new FileInfo(base.BaseLogFileName + ext).Length;
						}
					}
				}
				fileStream.Flush();
			}
			data.Close();
			fileStream.Close();
		}
	}
}
